package com.rt.tmpt.security.handler;

import com.rt.tmpt.dto.Result;
import org.springframework.security.authentication.*;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: wuxiaoyong
 * @Date: 2020/01/28
 * @Description: 认证失败的处理
 **/
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        //response.setContentType("application/json;charset=utf-8");
        Result result = new Result();
        if (exception instanceof UsernameNotFoundException ||
                exception instanceof BadCredentialsException
        ) {
            result.fault("账户名或密码输入错误!");
        } else if (exception instanceof LockedException) {
            result.fault("账户被锁定，请联系管理员!");
        } else if (exception instanceof CredentialsExpiredException) {
            result.fault("密码过期，请联系管理员!");
        } else if (exception instanceof AccountExpiredException) {
            result.fault("账户过期，请联系管理员!");
        } else if (exception instanceof DisabledException) {
            result.fault("账户被禁用，请联系管理员!");
        } else {
            result.fault("登录失败!"+exception.getLocalizedMessage());
        }
        //System.out.println(result.toString());
        //response.setStatus(401);
        result.response(response);
    }
}
